# -*- coding: utf-8 -*-
import json
import requests
import time
import random
import datetime


token = ''
CONFIG_FILE = "config.json"


def is_holiday(date=None):
    """检查指定日期是否为法定节假日（工作日返回False，节假日返回True）"""
    date = date or datetime.date.today().strftime("%Y-%m-%d")
    print(f"检查节假日: {date}")
    api_url = f"https://timor.tech/api/holiday/info/{date}"
    headers = {
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0"
    }
    try:
        response = requests.get(api_url, headers=headers).json()
        return response.get("type", {}).get("type") in (1, 2)  # 1=假日，2=节假日调休
    except:
        print('获取节假日失败:', requests.get(api_url, headers=headers))
        return False  # API失败时默认按非节假日处理


def read_token():
    global token
    """从配置文件读取Token，不存在时返回None"""
    try:
        with open(CONFIG_FILE, 'r') as f:
            config = json.load(f)
            token = config.get('token')
            print('读取token成功:', token)
    except (FileNotFoundError, json.JSONDecodeError, KeyError):
        return None


def write_token(new_token):
    global token
    """写入Token到配置文件"""
    config = {'token': 'Bearer ' + new_token}
    with open(CONFIG_FILE, 'w') as f:
        json.dump(config, f, indent=2)
        print('写入token成功:', config)
    token = new_token


def check_token():
    print('开始检查token是否有效')
    url = 'http://prod.tjssy.cn:2335/api/v1/home/todo/counter/all'
    headers = {
        "Authorization": token
    }
    response = requests.get(url, headers=headers)
    res = json.loads(response.text)
    print('\t', res)
    if res['code'] != 200:
        print('\ttoken失效', res['data'])
    else:
        print('\ttoken有效', res['data'])
    return res['code'] == 200


def refresh_token():
    print('开始登录获取新token')
    global token
    url = 'http://prod.tjssy.cn:2335/api/v1/login/login'
    data = {
        "pushId": "V6iRfG5RuXaNJLUWtBmNTr0WnWXYsoFnP5Xb8yswoO8wxnMOjLJDR2KBN+7yPegH",
        "password": "123456",
        "phone": "17600805308",
        "deviceId": "140fe1da9f9c168d563",
        "device": "mobile",
        "brand": "MIUI"
    }
    response = requests.post(url, data=data)
    res = json.loads(response.text)
    print('\t', res)
    if res['code'] != 200:
        print('\t登录失败', res['data'])
    else:
        print('\t登录成功', res['data'])
    token = res['data']['token']
    write_token(token)


def daka():
    print('开始打卡')
    sleep_time = random.randint(0, 600)
    print(f"\t等待{sleep_time}秒后开始打卡...")
    time.sleep(sleep_time)

    original_lat = 39.045622
    original_lon = 117.686315

    lat_variation = random.uniform(-0.0001, 0.0001)
    lon_variation = random.uniform(-0.0001, 0.0001)

    new_lat = round(original_lat + lat_variation, 6)
    new_lon = round(original_lon + lon_variation, 6)

    print(f"\t本次打卡坐标: {new_lat}, {new_lon}")

    headers = {
        "Authorization": token
    }
    data = {
        "MAC": "06:b8:e6:00:df:92",
        "address": "天津市滨海新区第四大街110号靠近58同城",
        "comment": None,
        "device": "Redmi",
        "field": False,
        "imageUrl": None,
        "latitude": str(new_lat),
        "longitude": str(new_lon),
        "model": "22021211RC",
        "uuid": "140fe1da9f9c168d563"
    }

    url = 'http://prod.tjssy.cn:2335/api/v1/attendance/checking'
    response = requests.post(url, headers=headers, data=data)
    res = json.loads(response.text)
    print('\t', res)
    if res['code'] != 200:
        print('\t打卡失败', res['data'])
    else:
        print('\t打卡成功', res['data']['result'], res['data']['address'])


if __name__ == '__main__':
    print('开始运行:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    if is_holiday():
        print('今天是节假日，不进行打卡')
    else:
        read_token()
        if not check_token():
            refresh_token()
        daka()
    print('结束运行:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    print('\n\n\n')
